package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author hm
 * @package com.sky.task
 * @date Created in 2024/11/23 14:49
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 每隔1分钟定时检查 是否存在未支付得订单，将状态改为取消
     */
    @Scheduled(cron = "0 * * * * ? ")
    public void processOutTimeOrder() {
        /**
         * 1.首先通过订单得状态（未支付）以及支付时间 ——》获取需要进行定时任务的订单
         * 2.推算时间（现在得时间-15minutes），将满足条件得订单状态修改为已超时
         */
        //时间加上-15，获得一个时间，根据sql语句判断是否有超过这个时间得，有就是订单超时得
//        LocalDateTime orderTime = LocalDateTime.now().plusMinutes(-15);
//        List<Orders> ordersList = ordersMapper.selectByStatusAndTime(Orders.PENDING_PAYMENT, orderTime);
//
//        if (ordersList.size() > 0 && ordersList != null) {
//            for (Orders order : ordersList) {
//                    order.setStatus(Orders.CANCELLED);
//                    order.setCancelReason("订单超时，自动取消");
//                    order.setCancelTime(LocalDateTime.now());
//                    ordersMapper.update(order);
//            }
//        }
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> orders = ordersMapper.selectByStatusAndTime(Orders.PENDING_PAYMENT, time);
        if (orders != null|| orders.size() > 0) {
            orders.forEach(order -> {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单超时，自动取消");
                order.setCancelTime(LocalDateTime.now());
                ordersMapper.update(order);
            });

        }
    }

    /**
     * 每天凌晨1点检查是否存在 还在配送中得订单，将状态修改为已完成
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder() {
        LocalDateTime orderTime = LocalDateTime.now().plusHours(-1);
        List<Orders> orders = ordersMapper.selectByStatusAndTime(Orders.DELIVERY_IN_PROGRESS, orderTime);
        if (orders != null && orders.size() > 0) {
            for (Orders order : orders) {
                order.setStatus(Orders.COMPLETED);
                order.setDeliveryTime(orderTime);
                ordersMapper.update(order);

            }
        }
    }

}
